package org.example.chat.handle;

import org.springframework.web.socket.*;

import java.io.IOException;
import java.time.LocalTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyWebSocketHandler implements WebSocketHandler {

    Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    // 当新连接建立时
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {
        System.out.println("客户端连接: " + session.getId());
        TextMessage textMessage = new TextMessage("欢迎加入！");
        sessionMap.put(session.getId(), session);
        session.sendMessage(textMessage);
    }

    // 处理客户端消息
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        String payload = (String) message.getPayload();
        System.out.println("收到消息: " + payload);

        // 模拟回复
        /*session.sendMessage("已收到: " + payload + " (时间: " + LocalTime.now() + ")".toTextMessage());*/
    }

    // 处理连接错误
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        System.err.println("连接错误: " + session.getId());
        exception.printStackTrace();
    }

    // 连接关闭时
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        System.out.println("连接关闭: " + session.getId() + " | 原因: " + status.getReason());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}